<?php

namespace App;

use App\Http\Services\FileManager;
use http\Env\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * App\MerchantMedicine
 *
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine query()
 * @mixin \Eloquent
 * @property int $id
 * @property int $merchant_id 商家id
 * @property string $name 药品名称
 * @property string $desc 描述
 * @property string $upc 条形码
 * @property string $sku_ssn 内部库存编号
 * @property string $approval_number 批准文号
 * @property string $specification 规格
 * @property int $thumb_id 商品封面图
 * @property float $selling_price 销售价格
 * @property int $stock 库存
 * @property int $classify_id
 * @property string $manufacturer 生产厂商名称
 * @property string $manufacturer_address 生产厂商地址
 * @property string $manufacturer_contact 生产厂商联系方式
 * @property string $electronic_regulatory_code 电子监管码
 * @property string|null $usage_and_dosage 用法用量
 * @property string|null $indications 适应症
 * @property string $adapt_to_the_crowd 适应人群
 * @property string $component 成分
 * @property string|null $adverse_reactions 不良反应
 * @property string|null $contraindications 禁忌
 * @property string|null $precautions 注意事项
 * @property string|null $interaction 药物相互作用
 * @property string|null $medication_for_children 儿童用药
 * @property string|null $medication_for_pregnancy_x_lactation 妊娠与哺乳用药
 * @property string|null $medication_for_aged 老年人用药
 * @property string $properties 性状
 * @property string $packing 包装
 * @property string $dosage_form 剂型
 * @property string $storage 贮藏
 * @property string|null $pharmacological_action 药理作用
 * @property string $expiry_date 有效期
 * @property string|null $detail 详情（富文本）
 * @property int $is_shop 是否上架，0：否 1：是
 * @property int $sort 商品排序，整数，数字越低排序越前
 * @property string|null $other_attribute_array 其他属性数组（json_encoded）
 * @property \Illuminate\Support\Carbon|null $deleted_at
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static bool|null forceDelete()
 * @method static \Illuminate\Database\Query\Builder|\App\MerchantMedicine onlyTrashed()
 * @method static bool|null restore()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereAdaptToTheCrowd($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereAdverseReactions($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereApprovalNumber($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereClassifyId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereComponent($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereContraindications($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereDeletedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereDesc($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereDetail($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereDosageForm($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereElectronicRegulatoryCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereExpiryDate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereIndications($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereInteraction($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereIsShop($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereManufacturer($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereManufacturerAddress($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereManufacturerContact($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereMedicationForAged($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereMedicationForChildren($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereMedicationForPregnancyXLactation($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereMerchantId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereOtherAttributeArray($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine wherePacking($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine wherePharmacologicalAction($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine wherePrecautions($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereProperties($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereSellingPrice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereSkuSsn($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereSort($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereSpecification($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereStock($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereStorage($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereThumbId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereUpc($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereUsageAndDosage($value)
 * @method static \Illuminate\Database\Query\Builder|\App\MerchantMedicine withTrashed()
 * @method static \Illuminate\Database\Query\Builder|\App\MerchantMedicine withoutTrashed()
 * @property string|null $ssn 商品编号
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereSsn($value)
 * @property string|null $simple_code 拼音简码
 * @property string|null $bit_code 本位码
 * @property string|null $nature_class 性质分类
 * @property string|null $use_class 用途分类
 * @property string|null $disease 主治疾病
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereBitCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereDisease($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereNatureClass($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereSimpleCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereUseClass($value)
 * @property string|null $drug_brand 商标
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereDrugBrand($value)
 * @property int $drug_type 药品分类：OTC甲乙、RX等
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereDrugType($value)
 * @property int $goods_type 0标准药品，1保健食品，2中药材、中药饮片/原料，3医疗器械，更多待增加
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereGoodsType($value)
 * @property int $water_num 水数量
 * @method static \Illuminate\Database\Eloquent\Builder|\App\MerchantMedicine whereWaterNum($value)
 */
class MerchantMedicine extends Model
{
    protected $table='merchant_medicine';
    use SoftDeletes;

    public static function getMedicineListItemInfo($merchant_medicine_id,$num=0){
        $data=self::whereId($merchant_medicine_id)
            ->first(['id','merchant_id','name','desc','upc','sku_ssn','drug_type',
                'specification','thumb_id','selling_price','stock','classify_id','is_shop',
                'sort','other_attribute_array','created_at','updated_at']);
        if ($data){
            $data->thumb_url=self::getMerchantMedicineImg($data->id);
            $data->classify_name=Classify::getClassifyName($data->classify_id);
            if ($num)
                $data->num=$num;
        }
        return $data ?? [];
    }
    public static function getMedicineDetailInfo($merchant_medicine_id){
        $data=self::whereId($merchant_medicine_id)->first();
        if ($data){
            $data->thumb_url=self::getMerchantMedicineImgList($data->id);
//            $data->classify_name=Classify::getClassifyName($data->classify_id);
            $data->merchant_name=Merchant::getMerchantName($data->merchant_id);
            $data->sku_list     = self::getMerchantMedicineSku($data->id);
            $data->discount_sales_rule_list = MerchantMedicine::getDiscountSalesRule($data->id);

            $classifyNameArr = '';
            $classifyPid = 0;
            $classifyList = MerchantMedicineXClassify::whereMerchantMedicineId($data->id)->get();
            if (count($classifyList) > 0) {
                foreach ($classifyList as $classify) {
                    $classifyName = Classify::getClassifyName($classify->classify_id);

                    $classifyInfo = Classify::whereId($classify->classify_id)->first();
                    if($classifyInfo && $classifyInfo->pid == 0){
                        $classifyPid = $classifyInfo->id;
                    }

                    if($classifyName){
                        if($classifyNameArr){
                            $classifyNameArr .= ' - ' . $classifyName;
                        }else{
                            $classifyNameArr = $classifyName;
                        }
                    }
                }
            }

            $data->classify_name = $classifyNameArr;
            $data->classify_first_id = $classifyPid;

        }
        return $data ?? [];
    }

    public static function getMerchantMedicineList($merchant_id,$page,$limit,$area=0){

        $data=self::whereMerchantId($merchant_id);
        if ($area){
            $medicine_ids=MerchantMedicineXArea::whereMerchantMedicineAreaId($area)
                ->pluck('merchant_medicine_id')
                ->toArray();
            $data=$data->whereIn('id',$medicine_ids);
        }
        $data=$data->offset($page * $limit)
            ->limit($limit)
            ->get();
        if (count($data) > 0){
            /** @var MerchantMedicine $item */
            foreach ($data as $item){
                $item->thumb_url=FileManager::getImgUrl($item->thumb_id);
            }
        }
        return $data;
    }
    public static function getSellingPrice($merchant_medicine_id){
        $data=self::whereId($merchant_medicine_id)->first();
        return $data ? $data->selling_price : 0;
    }

    public static function getMerchantMedicineImg($merchant_medicine_id){
        $merchantMedicineImg = MerchantMedicineImg::whereMerchantMedicineId($merchant_medicine_id)->first();
        if($merchantMedicineImg){
            $merchantMedicineImgUrl = FileManager::getImgUrl($merchantMedicineImg->img_id);
        }else{
            $merchantMedicineImgUrl = '';
        }

        return $merchantMedicineImgUrl;
    }

    public static function getMerchantMedicineImgList($merchant_medicine_id){
        $merchantMedicineImg = MerchantMedicineImg::whereMerchantMedicineId($merchant_medicine_id)->get();
        if(count($merchantMedicineImg) > 0){
            foreach ($merchantMedicineImg as $val) {
                $val->img_Url = FileManager::getImgUrl($val->img_id);
            }
        }

        return $merchantMedicineImg;
    }

    public static function getMerchantMedicineSku($merchant_medicine_id){
        $goodsSkuArr = MerchantMedicineSkuValue::whereMerchantMedicineId($merchant_medicine_id)->pluck('sku_id')->toArray();

        array_unique($goodsSkuArr);

        /** @var Sku $sku */
        $skuList = Sku::whereIn('id', $goodsSkuArr)->get();
        if (count($skuList) > 0) {
            foreach ($skuList as $sku) {
                $skuValueArr = [];
                $goodsSkuValueArr = MerchantMedicineSkuValue::whereMerchantMedicineId($merchant_medicine_id)->whereSkuId($sku->id)->get();
                if (count($goodsSkuValueArr) > 0) {
                    foreach ($goodsSkuValueArr as $goodsSkuValue) {
                        $skuValue = SkuValue::whereId($goodsSkuValue->sku_value_id)->first();
                        if ($skuValue) {
                            array_push($skuValueArr, $skuValue);
                        }
                    }
                }

                $sku->sku_value_list = $skuValueArr;
            }
        }

        return $skuList;
    }

    public static function getDiscountSalesRule($merchant_medicine_id){
        $medicineXDiscountList = DiscountXMedicine::whereMerchantMedicineId($merchant_medicine_id)->get();
        if(count($medicineXDiscountList) > 0){
            foreach ($medicineXDiscountList as $medicineXDiscount) {
                $discountRule = DiscountSalesRule::whereId($medicineXDiscount->discount_sales_rule_id)->first();

                $medicineXDiscount->discount_sales_rule_info = $discountRule;
            }
        }

        return $medicineXDiscountList;
    }

    /**
     * @param $goods_type
     * @return string
     */
    public static function getGoodsTypeName($goods_type){
        if ($goods_type == 0) return '标准药品';
        if ($goods_type == 1) return '保健食品';
        if ($goods_type == 2) return '中药材、中药饮片/原料';
        if ($goods_type == 3) return '医疗器械';
        return '类型'.$goods_type;
    }

    /**
     * @param $drug_type
     * @return string
     */
    public static function getDrugTypeName($drug_type){
        if ($drug_type == 0) return '普通商品/非处方药';
        if ($drug_type == 1) return '处方药(RX)';
        if ($drug_type == 2) return '甲类非处方药（红标OTC）';
        if ($drug_type == 3) return '乙类非处方药（绿标OTC）';
        return '类型'.$drug_type;
    }
    public static function getIsShopName($status){
        if ($status == 0) return '不显示';
        if ($status == 1) return '显示';
        return '状态'.$status;
    }
}
